﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace BP.OA
{
    public class GPM
    {
        //根据操作员的编号获取它的部门, 返回的列于 数据库GPM表 Port_Dept 列一致。
        public static DataTable GetUserDeptsOfDatatable(string user)
        {
            return CCPortal.API.GetUserDeptsOfDatatable(user);
        }

        //根据操作员的编号获取它的岗位, 返回的列于 数据库GPM表 Port_Station 列一致。
        public static DataTable GetUserStationsOfDatatable(string user)
        {
            return CCPortal.API.GetUserStationsOfDatatable(user);
        }

        //根据操作员的编号获取它的菜单. , 返回的列于 数据库GPM表 GPM_Menu 列一致。
        public static DataTable GetUserMenuOfDatatable(string user)
        {
            return CCPortal.API.GetUserMenuOfDatatable(user);
        }
        ////根据操作员的编号获取它的部门实体。
        //CCPortal.Depts enDepts = CCPortal.API.GetUserDeptOfEntities("zhangshan");

        ////根据操作员的编号获取它的岗位实体。
        //CCPortal.Stations enStations = CCPortal.API.GetUserStationsOfEntities("zhangshan");

        ////根据操作员的编号获取它的菜单实体。
        //CCPortal.Menus enMenus = CCPortal.API.GetUserMenuOfEntities("zhangshan");

        // 检查一个人员是否可以执行该功能?
        public static bool IsCanUseFunc
        {
            get
            {
                return CCPortal.API.IsCanUseFunc("zhangshan", "MyFuncNo");
            }
        }
        //****************************************************************************************
        #region //存储变量
        private static DataTable _AllDepts_By_Tree = null;
        private static DataTable _AllDepts = null;
        private static DataTable _AllStations = null;
        private static DataTable _AllEmps = null;
        #endregion
        //以下函数是为了Depts,Stations,Emps的检索而用
        public static DataTable GetAllDepts_By_Tree()
        {
            if (_AllDepts_By_Tree == null)
            {
                string sSql = "exec dbo.sp_get_tree_table 'Port_Dept','No','Name','ParentNo','No','0',0,4";
                _AllDepts_By_Tree = CCPortal.DA.DBAccess.RunSQLReturnTable(sSql);
            }
            return _AllDepts_By_Tree;
        }
        public static DataTable GetAllDepts()
        {
            if (_AllDepts == null)
            {
                string sSql = "Select * from Port_Dept";
                _AllDepts = CCPortal.DA.DBAccess.RunSQLReturnTable(sSql);
            }
            return _AllDepts;
        }
        public static DataTable GetAllStations()
        {
            if (_AllStations == null || _AllStations.Rows.Count ==0)
            {
                string sSql = "select A.No,'('+B.Name+')'+A.Name as Name from Port_Station A"
                              + " inner join Port_StationType B on A.FK_StationType=B.No"
                              + " order by A.FK_StationType";
                if (BP.Sys.SystemConfig.AppCenterDBType == BP.DA.DBType.MySQL)
                {
                    sSql = "select A.No,CONCAT('(',B.Name,')',A.Name) as Name from Port_Station A"
                            + " inner join Port_StationType B on A.FK_StationType=B.No"
                            + " order by A.FK_StationType";
                }
                _AllStations = CCPortal.DA.DBAccess.RunSQLReturnTable(sSql);
            }
            return _AllStations;
        }
        public static DataTable GetAllEmps()
        {
            if (_AllEmps == null)
            {
                string sSql = "select * from Port_Emp";
                _AllEmps = CCPortal.DA.DBAccess.RunSQLReturnTable(sSql);
            }
            return _AllEmps;
        }
        public static DataTable GetFilteredEmps(string empList, string deptList, string stationList)
        {
            string sql = String.Format("select * from Port_Emp"
                           + " where ('{0}'='' or charIndex(','+No+',',',{0},')>0)"
                           + " and ('{1}'='' or No in (select FK_Emp from Port_EmpDept where charIndex(','+FK_Dept+',',',{1},')>0))"
                           + " and ('{2}'='' or No in (select FK_Emp from Port_EmpStation where charIndex(','+FK_Station+',',',{2},')>0))"
                           , empList, deptList, stationList);
            if (BP.Sys.SystemConfig.AppCenterDBType == BP.DA.DBType.MySQL)
            {
                sql = String.Format("select * from Port_Emp"
                                + " where ('{0}'='' or FIND_IN_SET(No,',{0},')>0)"
                                + " and ('{1}'='' or No in (select FK_Emp from Port_EmpDept where FIND_IN_SET(FK_Dept,',{1},')>0))"
                                + " and ('{2}'='' or No in (select FK_Emp from Port_EmpStation where FIND_IN_SET(FK_Station,',{2},')>0))"
                                , empList, deptList, stationList);
            }
            return CCPortal.DA.DBAccess.RunSQLReturnTable(sql);
        }

        public static DataTable GetFilteredEmps_BPM(string empList, string deptList, string stationList)
        {
            string sql = String.Format("select * from Port_Emp"
                           + " where ('{0}'='' or charIndex(','+No+',',',{0},')>0)"
                           + " and ('{1}'='' or No in (select FK_Emp from Port_DeptEmp where charIndex(','+FK_Dept+',',',{1},')>0))"
                           + " and ('{2}'='' or No in (select FK_Emp from Port_DeptEmpStation where charIndex(','+FK_Station+',',',{2},')>0))"
                           , empList, deptList, stationList);
            if (BP.Sys.SystemConfig.AppCenterDBType == BP.DA.DBType.MySQL)
            {
                sql = String.Format("select * from Port_Emp"
                            + " where ('{0}'='' or FIND_IN_SET(No,',{0},')>0)"
                            + " and ('{1}'='' or No in (select FK_Emp from Port_EmpDept where FIND_IN_SET(FK_Dept,',{1},')>0))"
                            + " and ('{2}'='' or No in (select FK_Emp from Port_EmpStation where FIND_IN_SET(FK_Station,',{2},')>0))"
                            , empList, deptList, stationList);
            }
            return CCPortal.DA.DBAccess.RunSQLReturnTable(sql);
        }
        public static DataTable GetSearchedEmpOA(string deptId, bool searchChildDept, string stationId, string name)
        {
            if (searchChildDept)
                deptId = GetDeptAndChild(deptId);
            else
                deptId = "'" + deptId + "'";
            string filter_dept = deptId == "0" ? String.Empty : String.Format(" and Port_Emp.No in (Select FK_Emp from Port_EmpDept where FK_Dept in ({0}))", deptId);
            string filter_station = stationId == "0" ? String.Empty : String.Format(" and Port_Emp.No in (Select FK_Emp from Port_EmpStation where FK_Station='{0}')", stationId);
            string filter_name = String.IsNullOrEmpty(name) ? String.Empty : String.Format(" and Port_Emp.Name+','+Port_Emp.NO like '%{0}%'", name);
            if (BP.Sys.SystemConfig.AppCenterDBType == BP.DA.DBType.MySQL)
            {
                filter_name = String.IsNullOrEmpty(name) ? String.Empty : String.Format(" and CONCAT(Port_Emp.Name,',',Port_Emp.NO) like '%{0}%'", name);
            }
            string sql = String.Format("select Port_Emp.*,Port_Dept.Name as DeptName from Port_Emp,Port_Dept where Port_Emp.FK_Dept = Port_Dept.No {0}{1}{2}", filter_dept, filter_station, filter_name);
            return CCPortal.DA.DBAccess.RunSQLReturnTable(sql);
        }
        public static DataTable GetSearchedEmps(string deptId, bool searchChildDept, string stationId, string name)
        {
            if (searchChildDept)
                deptId = GetDeptAndChild(deptId);
            else
                deptId = "'" + deptId + "'";

            string filter_dept = deptId == "0" ? String.Empty : String.Format(" and Port_Emp.No in (Select FK_Emp from Port_DeptEmp where FK_Dept in ({0}))", deptId);
            string filter_station = stationId == "0" ? String.Empty : String.Format(" and Port_Emp.No in (Select FK_Emp from Port_DeptEmpStation where FK_Station='{0}')", stationId);
            string filter_name = String.IsNullOrEmpty(name) ? String.Empty : String.Format(" and Port_Emp.Name+','+Port_Emp.NO like '%{0}%'", name);
            if (BP.Sys.SystemConfig.AppCenterDBType == BP.DA.DBType.MySQL)
            {
                filter_name = String.IsNullOrEmpty(name) ? String.Empty : String.Format(" and CONCAT(Port_Emp.Name,',',Port_Emp.NO) like '%{0}%'", name);
            }
            string sql = String.Format("select Port_Emp.*,Port_Dept.Name as DeptName from Port_Emp,Port_Dept where Port_Emp.FK_Dept = Port_Dept.No {0}{1}{2}", filter_dept, filter_station, filter_name);
            return CCPortal.DA.DBAccess.RunSQLReturnTable(sql);
        }

        /// <summary>
        /// 获取本部门与子级部门
        /// </summary>
        /// <returns></returns>
        private static string GetDeptAndChild(string deptId)
        {
            string strDepts = "'" + deptId + "'";
            GetChildDept(deptId, ref strDepts);
            return strDepts;
        }

        /// <summary>
        /// 增加子级
        /// </summary>
        /// <param name="parentNo"></param>
        /// <param name="depts"></param>
        private static void GetChildDept(string parentNo, ref string strDepts)
        {
            BP.Port.Depts depts = new Port.Depts(parentNo);
            if (depts != null && depts.Count > 0)
            {
                foreach (BP.Port.Dept item in depts)
                {
                    strDepts += ",'" + item.No + "'";
                    GetChildDept(item.No, ref strDepts);
                }
            }
        }

        public static bool IsCanUseFun(string userNo, string funcNo)
        {
            return CCPortal.API.IsCanUseFunc(userNo, funcNo);
        }
        //以下四个函数为Auth扩展
        /// <summary>
        /// 当前用户权限访问
        /// </summary>
        /// <param name="funcNo"></param>
        /// <returns></returns>
        public static bool IsCanUseFun(string funcNo)
        {
            if (String.IsNullOrEmpty(funcNo)) return true;
            return CCPortal.API.IsCanUseFunc(BP.Web.WebUser.No, funcNo);
        }
        /// <summary>
        /// 验证用户是否可以访问当前页面，不能访问则直接跳到无权查看信息页
        /// </summary>
        /// <param name="userNo">用户登录编号</param>
        public static void CheckUserCanLookThisPage(string userNo)
        {
            var menuTable = GetUserMenuOfDatatable(userNo);
            var isCan = false;

            foreach(DataRow dr in menuTable.Rows)
            {
                if (dr["Url"] == DBNull.Value || dr["Url"] == null || string.IsNullOrWhiteSpace(dr["Url"].ToString()))
                    continue;

                //替换
                dr["Url"] = dr["Url"].ToString()
                    .Replace("@WebUser.FK_Dept", BP.Web.WebUser.FK_Dept)
                    .Replace("@WebUser.No", BP.Web.WebUser.No);

                if(HttpContext.Current.Request.RawUrl.IndexOf(dr["Url"].ToString()) != -1)
                {
                    isCan = true;
                    break;
                }

                //如果Url中没有，再判断Tag1/Tag2/Tag3中是否有，有则通过
                if (dr["Tag1"] != DBNull.Value && dr["Tag1"] != null && !string.IsNullOrWhiteSpace(dr["Tag1"].ToString()))
                {
                    dr["Tag1"] = dr["Tag1"].ToString()
                        .Replace("@WebUser.FK_Dept", BP.Web.WebUser.FK_Dept)
                        .Replace("@WebUser.No", BP.Web.WebUser.No);

                    if (HttpContext.Current.Request.RawUrl.IndexOf(dr["Tag1"].ToString()) != -1)
                    {
                        isCan = true;
                        break;
                    }
                }

                if (dr["Tag2"] != DBNull.Value && dr["Tag2"] != null && !string.IsNullOrWhiteSpace(dr["Tag2"].ToString()))
                {
                    dr["Tag2"] = dr["Tag2"].ToString()
                        .Replace("@WebUser.FK_Dept", BP.Web.WebUser.FK_Dept)
                        .Replace("@WebUser.No", BP.Web.WebUser.No);

                    if (HttpContext.Current.Request.RawUrl.IndexOf(dr["Tag2"].ToString()) != -1)
                    {
                        isCan = true;
                        break;
                    }
                }

                if (dr["Tag3"] != DBNull.Value && dr["Tag3"] != null && !string.IsNullOrWhiteSpace(dr["Tag3"].ToString()))
                {
                    dr["Tag3"] = dr["Tag3"].ToString()
                        .Replace("@WebUser.FK_Dept", BP.Web.WebUser.FK_Dept)
                        .Replace("@WebUser.No", BP.Web.WebUser.No);

                    if (HttpContext.Current.Request.RawUrl.IndexOf(dr["Tag3"].ToString()) != -1)
                    {
                        isCan = true;
                        break;
                    }
                }
            }

            if(!isCan)
            {
                RedirectNoAccess();
            }
        }
        public static void RedirectErrorPage(string error)
        {
            HttpContext.Current.Response.Redirect(String.Format("/Main/Error.aspx?msg={0}", error));
        }
        public static void RedirectNoAccess()
        {
            HttpContext.Current.Response.Redirect(String.Format("/Main/Error.aspx?msg={0}", "你没有权限访问此功能"));
        }
        public static string GetUserAuth(string userNo)
        {
            string sql = String.Format("select SID from Port_Emp where [No]='{0}'", userNo);
            return CCPortal.DA.DBAccess.RunSQLReturnString(sql);
        }
        //以下六个函数都是从id获取名称
        public static string GetUserNames(string userNames)
        {
            List<String> l_users = new List<string>();
            foreach (DataRow dr in GetAllEmps().Rows)
            {
                if (String.Format(",{0},", userNames).Contains(String.Format(",{0},", Convert.ToString(dr["No"]))))
                    l_users.Add(String.Format("{0}", dr["Name"]));
            }
            return String.Join(",", l_users.ToArray());
        }
        public static string GetDeptNames(string depts)
        {
            List<String> l_depts = new List<string>();
            foreach (DataRow dr in GetAllDepts().Rows)
            {
                if (String.Format(",{0},", depts).Contains(String.Format(",{0},", Convert.ToString(dr["No"]))))
                    l_depts.Add(String.Format("{0}", dr["Name"]));
            }
            return String.Join(",", l_depts.ToArray());
        }
        public static string GetStationNames(string stations)
        {
            List<String> l_stations = new List<string>();
            foreach (DataRow dr in GetAllStations().Rows)
            {
                if (String.Format(",{0},", stations).Contains(String.Format(",{0},", Convert.ToString(dr["No"]))))
                    l_stations.Add(String.Format("{0}", dr["Name"]));
            }
            return String.Join(",", l_stations.ToArray());
        }
        public static String GetUserName_By_No(string userNo)
        {
            DataTable dt = GetAllEmps();
            DataRow[] drs = dt.Select(String.Format("No='{0}'", userNo));
            if (drs.Length == 0) return null;
            return String.Format("{0}", drs[0]["Name"]);
        }
        public static String GetDeptName_By_No(string deptNo)
        {
            DataTable dt = GetAllDepts();
            DataRow[] drs = dt.Select(String.Format("No='{0}'", deptNo));
            if (drs.Length == 0) return null;
            return String.Format("{0}", drs[0]["Name"]);
        }
        public static String GetStationName_By_No(string stationNo)
        {
            DataTable dt = GetAllStations();
            DataRow[] drs = dt.Select(String.Format("No='{0}'", stationNo));
            if (drs.Length == 0) return null;
            return String.Format("{0}", drs[0]["Name"]);
        }
    }
}
